#!/usr/bin/env python

import os
import sys
import subprocess
import re
import time
import _thread
import common

icon_fg = common.black
icon_bg = common.blue
icon_tr = "0xff"
text_fg = common.black
text_bg = common.blue
text_tr = "0xff"

icon_color = "^c" + str(icon_fg) + "^^b" + str(icon_bg) + str(icon_tr) + "^"
text_color = "^c" + str(text_fg) + "^^b" + str(text_bg) + str(text_tr) + "^"
DELAY_TIME = 1

filename = os.path.basename(__file__)
name = re.sub(r"\..*", '', filename)

vol_text = "--"
vol_icon = "ﱝ"
volumuted = ""

def get_connected_bluetooth_device():
    """
    通过检查默认音频输出获取蓝牙设备状态
    返回: 如果有蓝牙设备连接返回True，否则返回False
    """
    try:
        # 检查默认音频输出是否为蓝牙设备
        cmd = "pactl info | grep 'Default Sink' | grep -i bluez"
        result = subprocess.run(cmd, shell=True, timeout=2, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        
        # 如果命令成功执行且输出中包含bluez，说明有蓝牙设备连接
        return result.returncode == 0
        
    except Exception:
        return False

def GetBluetoothBatteryByBluetoothctl():
    try:
        # 检查是否有蓝牙设备连接
        has_bluetooth = get_connected_bluetooth_device()
        
        if not has_bluetooth:
            return "󱔑"  # 没有连接的蓝牙设备
        
        # 如果有蓝牙设备连接，但无法获取具体电池信息，显示连接图标
        return "󰂱"  # 蓝牙连接图标（表示已连接但无电池信息）
    
    except Exception:
        return "󱔑"  # 错误状态

def get_vol_content():
    global vol_text
    global vol_icon
    global volumuted

    try:
        cmd = "pactl info | grep 'Default Sink' | awk '{print $3}'"
        result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        sink = str(result.stdout.replace('\n', ''))
        
        if not sink:
            vol_text = "--"
            vol_icon = "ﱝ"
            volumuted = ""
            bluetooth_battery = GetBluetoothBatteryByBluetoothctl()
            return f"{vol_icon}{vol_text}% {bluetooth_battery}"
        
        cmd = f"pactl list sinks | grep '{sink}' -A 6 | grep 'Mute:' | grep -q 'no'; echo $?"
        result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        volumuted = (result.stdout.strip() == "0")
        
        cmd = f"pactl list sinks | grep '{sink}' -A 7 | grep 'Volume:' | head -1 | awk '{{printf int($5)}}'"
        result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        vol_text = str(result.stdout.replace('\n', ''))
        
        if not volumuted:
            vol_text = "--"
            vol_icon = "ﱝ"
        else:
            try:
                vol = int(vol_text) if vol_text.isdigit() else 0
                if vol == 0: 
                    vol_icon = "婢"
                    vol_text = "00"
                else:
                    vol_icon = "墳 "
            except ValueError:
                vol_text = "--"
                vol_icon = "ﱝ"
        
        # 使用简化方法获取蓝牙状态
        bluetooth_battery = GetBluetoothBatteryByBluetoothctl()
        
        return f"{vol_icon}{vol_text}% {bluetooth_battery}"
    
    except Exception:
        return f"ﱝ--% 󱔑"

def update(loop=False, exec=True):
    while True:
        try:
            icon = " " + get_vol_content() + " "
            txt = "^s" + str(name) + "^" + str(icon_color) + str(icon) + str(text_color)
            common.write_to_file(txt + "\n", str(name))
            if not loop:
                if exec:
                    os.system("xsetroot -name '" + str(txt).replace("'", "'\\''") + "'")
                break
            time.sleep(DELAY_TIME)
        except Exception:
            time.sleep(DELAY_TIME)

def update_thread():
    _thread.start_new_thread(update, (False, False))

def notify(string=''):
    try:
        global vol_text
        global vol_icon
        global volumuted
        get_vol_content()

        cmd = ""
        if not volumuted:
            cmd = "notify-send -r 9527 '婢  mute'"
        else:
            cmd = f"notify-send -r 9527 -h int:value:{vol_text} -h string:hlcolor:#dddddd '{vol_icon} Volume'"
        os.system(cmd)
    except Exception:
        pass

def click(string=''):
    try:
        if string == 'L':
            notify()
        elif string == 'M':
            os.system("pactl set-sink-mute @DEFAULT_SINK@ toggle")
            notify()
        elif string == 'R':
            os.system("killall pavucontrol 2>/dev/null || pavucontrol --class floatingTerminal &")
        elif string == 'U':
            os.system("pactl set-sink-volume @DEFAULT_SINK@ +5%")
            notify()
        elif string == 'D':
            os.system("pactl set-sink-volume @DEFAULT_SINK@ -5%")
            notify()
    except Exception:
        pass

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] == "update":
            pass
        elif sys.argv[1] == "notify":
            notify()
        else:
            update(exec=False)
            click(sys.argv[1])
            update(exec=False)
    else:
        update()
